package com.longzz.service.impl;

import com.longzz.bean.Danmu;
import com.longzz.service.DanmuService;
import com.longzz.util.FileUtil;
import com.longzz.util.HttpUtil;
import lombok.extern.log4j.Log4j;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by longzzz on 2018/6/27.
 */
@Service("danmuService")
@Log4j
public class DanmuServiceImpl implements DanmuService{

    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HttpUtil httpUtil;

    @Override
    public void export(String url,HttpServletResponse response) throws Exception {
        // 生成Excel文档
        XSSFWorkbook workBook = generateExcel(spider(url));

        // 导出流到浏览器
        ServletOutputStream out = null;
        try {
            response.setContentType("text/html;charset=utf-8");
            if (workBook == null) {
                response.getWriter().print("下载文件出错！该文件不存在！");
                return;
            }
            // 写流文件到前端浏览器
            out = response.getOutputStream();
            response.setCharacterEncoding("utf-8");
            Date curDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileUtil.encodingFileName("弹幕_" + sdf.format(curDate) + ".xlsx"));
            workBook.write(out);
        } catch (IOException e) {
            log.error("下载文件失败", e);
            response.getWriter().write("操作失败！未知错误");
        } finally {
            try {
                if (workBook != null) {
                    workBook.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.error("下载文件失败", e);
                response.getWriter().write("操作失败！未知错误");
            }
        }

    }
    public List<Danmu> spider(String url){
        List<Danmu> danmuList = null;
        try {
            danmuList = httpUtil.getDanmu(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  danmuList;
    }

    public XSSFWorkbook generateExcel(List<Danmu> danmuList) {
        XSSFWorkbook workBook = new XSSFWorkbook();
        XSSFSheet sheet = workBook.createSheet("弹幕列表");

        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 生成一个字体
        XSSFFont font = workBook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);

        // 定义标题样式
        XSSFCellStyle titleStyle = workBook.createCellStyle();
        titleStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        titleStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        // titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        titleStyle.setWrapText(true);
        titleStyle.setFont(font);
        // 定义通用样式
        XSSFCellStyle commonStyle = workBook.createCellStyle();
        // commonStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        commonStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        commonStyle.setWrapText(true);
        // 创建标题行
        XSSFRow row = sheet.createRow(0);
        SimpleDateFormat formatDateTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        row.createCell(0).setCellValue("时间");
        row.createCell(1).setCellValue("弹幕内容");
        row.createCell(2).setCellValue("发送时间");

        // 设置标题样式
        row.getCell(0).setCellStyle(titleStyle);
        row.getCell(1).setCellStyle(titleStyle);
        row.getCell(2).setCellStyle(titleStyle);

        for (int i = 0; i < danmuList.size(); i++) {
            Danmu danmu = danmuList.get(i);
            XSSFRow dataRow = sheet.createRow(i + 1);
            dataRow.createCell(0).setCellValue(danmu.getTime());
            dataRow.createCell(1).setCellValue(danmu.getContent());
            dataRow.createCell(2).setCellValue(formatDateTime.format(danmu.getSendDateTime()));
        }

        return workBook;

    }

}
